package com.graduation.lastproject.controller.home.homeBasicActive;


import com.graduation.lastproject.entity.User;
import com.graduation.lastproject.service.home.HomeBasicActice.HomeService;
import com.graduation.lastproject.util.shiro.LoginsToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Controller
public class HomeController {
    private static Logger logger=LoggerFactory.getLogger(HomeController.class);
    @Autowired
    HomeService homeService;
    @Value("${login.user}")
    private String loginType;

  /*  @RequestMapping(value = "home")
    public  String hello(HttpServletRequest request,String id){
        return "home";
    }*/

    @RequestMapping(value = "{page}")
    public String topages(@PathVariable String page,HttpServletRequest request){
        //@PathVariable 映射url地址占位符的参数 到方法参数中；
        /*System.out.println("返回地址:"+page);*/
        if(page.equals("register")){
           request.setAttribute("type","注册");
           return "home/register";
        }
        if(page.equals("update")){
            /*User user=(User) SecurityUtils.getSubject().getPrincipal();*/
      /*    Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            User userOld= (User)session.getAttribute("userInfo");*/
            User user=(User)request.getSession().getAttribute("userInfo");
            request.setAttribute("entry",user);
            request.setAttribute("type","更新");
            return "home/register";
        }
        String pages="home/"+page;
        return pages;
    }

    //用户注册
    @RequestMapping(value="/registered", method = RequestMethod.POST )
    @ResponseBody
    public Object loginin(HttpServletRequest request){
        Map<String,Object> result = new HashMap<>();
        Map<String, Object> map = parameters(request);
        //判断电话是否存在
        boolean f=homeService.getUserPhone(map.get("phone").toString());
        if(!f){
        int i=homeService.login(map);
        result.put("msg",i==1 ? "注册成功" : "注册失败");
        }else {
            result.put("msg","电话已被使用,请更换另一号码");
        }
        return result;
    }

    //用户登录
    @RequestMapping(value = "/logined",method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        //1 获取Subject
        Subject subject= SecurityUtils.getSubject();
        /*if(!subject.isAuthenticated()){   */
            //创建令牌，封装用户数据
            LoginsToken token=new  LoginsToken(request.getParameter("realname"),request.getParameter("password"),loginType);;
               try {
                   subject.login(token);
                   String userState=((User)request.getSession().getAttribute("userInfo")).getState()+"";
                   String userReason=((User)request.getSession().getAttribute("userInfo")).getReason()+"";
                   if(userState.equals("1")){
                      request.getSession().removeAttribute("user");
                   }
                   result.put("msg","登录成功");
                   result.put("userState",userState);
                   result.put("userReason",userReason);
                   return result;
               }catch (UnknownAccountException e){
                   result.put("msg","登录名未注册,登录失败");
                   return result;
               }catch (IncorrectCredentialsException e){
                   result.put("msg","密码错误,登录失败");
                   return result;
               }
        /*}*/
    }
    //用户退出
    @RequestMapping("/logout")
    public String logout() {
       /* Subject subject = SecurityUtils.getSubject();//取出当前验证主体
        if (subject != null) {
            subject.logout();//不为空，执行一次logout的操作，将session全部清空
        }*/
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.removeAttribute("userInfo");
        session.removeAttribute("user");
        return "home/home";
    }


    /**
     * 用户信息修改
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST )
    @ResponseBody
    public Object update(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        Map<String, Object> map = parameters(request);
        /*信息修改电话也不可与库中文件重复*/
        boolean f=homeService.getUserPhone(map.get("phone").toString());
        if(!f){
            int i=homeService.updateInfo(map);
            result.put("msg",i == 1 ? "更新成功" : "更新失败");
            logout();
        }else {
            result.put("msg","电话已被使用,请更换另一号码");
        }
        return result;
    }


    /** request转map */
    private final Map<String, Object> parameters(HttpServletRequest request) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        if (request != null) {
            Enumeration<String> keys = request.getParameterNames();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                try {
                    parameters.put(key, request.getParameter(key));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return parameters;
    }

}
